import router from '@/router'
import store from '@/store'
import axios from 'axios'
import qs from 'qs'
import { Dialog, Notify } from 'vant'
import { getDomain, getToken } from './auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 30, // request timeout
  paramsSerializer(params) {
    return qs.stringify(params)
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const timestamp = new Date().getTime();

    config.baseURL = getDomain();

    if (
      Object.prototype.toString.call(config.params) === '[object Object]' &&
      typeof config.params._ === 'undefined'
    ) {
      config.params._ = timestamp;
    } else if (
      Object.prototype.toString.call(config.params) === '[object URLSearchParams]' &&
      config.params.has('_') === false
    ) {
      config.params.set('_', timestamp);
    } else {
      config.params = { _: timestamp };
    }

    if (store.getters.token) {
      // let each request carry token
      // ['token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
      if (config.method == 'post') {
        if (Object.prototype.toString.call(config.data) === '[object Object]') {
          config.data['Token'] = getToken()
        } else if (!config.data) {
          config.data = { Token: getToken() }
        }
      } else {
        config.params['Token'] = getToken()
        let pageModel = config.params['pageModel']
        Object.prototype.toString.call(pageModel) == '[object Object]' && (pageModel['Token'] = getToken())
      }

    }

    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  ({ data, config }) => {
    // 对响应数据做点什么
    let returnData

    if (data.ErrorCode == 0) {
      returnData = data
      config.successMsg && Notify({ type: 'success', message: typeof config.successMsg === 'string' ? config.successMsg : data.ErrorMsg || '操作成功' })
    }
    else if (data.ErrorCode == 1) {
      returnData = Promise.reject(data)

      Dialog.confirm({
        message: '登录信息已失效，要重新登录吗？',
        confirmButtonText: '重登',
        cancelButtonText: '取消'
      }).then(() => {

        router.replace({
          name: "login",
        });

      }).catch(() => {
        // on cancel
      })

    } else {
      returnData = Promise.reject(data)
      if (config.failMsg) Notify({ type: 'warning', message: typeof config.failMsg === 'string' ? config.failMsg : data.ErrorMsg || '操作失败' })

    }

    return returnData;
  }, error => {
    // 对响应错误做点什么
    Notify.clear()
    // Notify({ type: 'danger', message: '服务开小差了，请重试~' });
    return Promise.reject(error);
  }
);

export default service